#include "stdafx.h"
#include "Terrain.h"


Terrain::Terrain() :
Solid(nullptr),
Food(nullptr),
TileCount(0),
Size(0)
{
}

Terrain::~Terrain()
{
	if (Solid != nullptr)
		delete Solid;

	if (Food != nullptr)
		delete Food;
}

void Terrain::Declare(unsigned int NewSize)
{
	TileCount = NewSize*NewSize;
	Size = NewSize;

	if (Solid != nullptr)
		delete Solid;
	Solid = new bool[TileCount];

	if (Food != nullptr)
		delete Food;
	Food = new bool[TileCount];

}

void Terrain::Genertate(unsigned int Ratio, unsigned int Smooth)
{
	bool* BufferState = new bool[TileCount];

	//zufallsstreuung
	for (int n = 0; n < TileCount; ++n)
		BufferState[n] = (rand() % 100 > Ratio ? true : false);

	//Rahmen
	for (int n = 0; n < Size; ++n)
	{
		BufferState[n] = true;
		BufferState[n + Size * (Size - 1)] = true;
		BufferState[n * Size] = true;
		BufferState[n * Size + (Size - 1)] = true;
	}

	//zufallsstreuung
	for (int n = 0; n < TileCount * Smooth; ++n)
	{
		//Zufallsposition
		const int x = 1 + (rand() % (Size - 2));
		const int y = 1 + (rand() % (Size - 2));

		//umgebungswert
		const int t0 = (x - 1) + (y - 1) * Size;
		const int t1 = (x - 1) + (y)* Size;
		const int t2 = (x - 1) + (y + 1) * Size;
		const int t3 = (x)+(y - 1) * Size;
		const int t4 = (x)+(y)* Size;
		const int t5 = (x)+(y + 1) *  Size;
		const int t6 = (x + 1) + (y - 1) * Size;
		const int t7 = (x + 1) + (y)* Size;
		const int t8 = (x + 1) + (y + 1) * Size;
		const int Value = (int)BufferState[t0] + (int)BufferState[t1] + (int)BufferState[t2] + (int)BufferState[t3] + (int)BufferState[t4] + (int)BufferState[t5] + (int)BufferState[t6] + (int)BufferState[t7] + (int)BufferState[t8];

		if (Value > 4)
			BufferState[t4] = true;
		else
			BufferState[t4] = false;
	}

	//buffer kopieren
	for (int n = 0; n < TileCount; ++n)
		Solid[n] = BufferState[n];

	delete BufferState;
}

